import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'
import { addClassName, removeClassName } from 'app/shared/utils/dom-helpers'

declare var $: any
@Component({
  selector: 'sa-corporate-account',
  templateUrl: './corporate-account.component.html'
})
export class CorporateAccountComponent implements OnInit {
  validatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      accountType: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择账户类型'
          }
        }
      },
      accountName: {
        validators: {
          notEmpty: {
            message: '请输入账户名称'
          }
        }
      }
    }
  }
  tableData: any[] = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  threeStateText: boolean = true
  companyArrays: any[] = []
  companyData: any[] = []

  inputApi: string = 'company/companyTreeByCompanyId.html'
  inputParam = {
    companyId: ''
  }

  CorporateAccountFrom: any = {
    id: '',
    companyId: '',
    companyName: '',
    factoryArr: [],
    accountType: '',
    accountName: '',
    remark: ''
  }
  paramFormat: any = {
    id: 'id',
    text: 'text'
  }
  companyList: any = []
  formType: string = 'new'

  tableSearch: any = {
    // companyId: "",
    // companyName: "",
    companyFacotoryId: '',
    accountType: '',
    accountName: ''
  }

  startTime: string = ''
  endTime: string = ''
  apiList: any //用户数据
  interfaceKey: string = '' //接口ID
  interfaceName: string = '' //接口名称

  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
    })
  }
  //点击对接厂区
  companySelectedClick() {
    if (!this.CorporateAccountFrom.companyName) {
      this.jsonApiService.message('请先选择项目')
      $('#controlTreeCompany .s_tree_box.s_tree_box_width').removeClass('tree_open')
      return
    } else {
      $('#controlTreeCompany .s_tree_box.s_tree_box_width').addClass('tree_open')
    }
  }
  //对接厂区回调
  addCompanySelected(data) {
    let arr = []
    data.companySelectedList.map(item => {
      arr.push({
        factoryId: item.companyId,
        factoryName: item.companyName
      })
    })
    this.CorporateAccountFrom.factoryArr = arr
  }

  //公司[项目]选中回调
  companySelected(data) {
    this.tableSearch.companyFacotoryId = data.companyId
    // this.tableSearch.companyId = data.companyId;
    // this.tableSearch.companyName = data.companyName;
  }
  //公司[项目]选中回调
  companySelectedForm(data) {
    this.CorporateAccountFrom.companyId = data.companyId
    this.CorporateAccountFrom.companyName = data.companyName
  }

  //项目选中
  optionSelected(data) {
    this.tableSearch.companyId = data.id
    this.tableSearch.companyName = data.text
  }
  //项目选中
  optionSelectedForm(data) {
    this.CorporateAccountFrom.companyId = data.id
    this.CorporateAccountFrom.companyName = data.text
    this.inputParam.companyId = data.id
    this.companyArrays = []
  }

  ngOnInit() {
    this.load()
    this.getCompanyList()
  }
  // 项目
  getCompanyList(companyId?: string) {
    this.jsonApiService
      .http_obj('company/queryCompanyList.html', {
        isStreamline: true,
        companyId
      })
      .subscribe(data => {
        if (data.success) {
          if (companyId) {
            this.companyData = data.data
          } else {
            this.companyList = data.data
          }
        }
      })
  }
  //table刷新
  refresh() {
    this.load()
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    this.load()
  }
  //初始化加载list数据
  load() {
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: this.tableSearch
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('CorporAccount/page.html', reqdata).subscribe(data => {
      if (data.isSuccess) {
        data.exhibitDatas.forEach(item => {
          item.factoryName = ''
          item.factoryArr.forEach((element, i) => {
            item.factoryName += `${element.factoryName}${item.factoryArr.length - 1 > i ? ',' : ''}`
          })
        })
        this.tableData = data.exhibitDatas
        this.totalCount = data.recordCount
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }
  //删除
  delRow(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      this.jsonApiService
        .http_obj('CorporAccount/deleteById.html', {
          id: row.id
        })
        .subscribe(data => {
          this.jsonApiService.message(data.message)
          if (data.success) {
            this.load()
          }
        })
    })
  }

  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  /*
   * 新增
   */
  table_add(modal) {
    modal.show()
    this.resetForm()
    this.formType = 'new'
  }
  /*
   * 编辑
   */
  editRow(row, modal) {
    modal.show()
    this.resetForm()
    //		this.CorporateAccountFrom.id = row.id;
    this.formType = 'updata'
    for (let item in this.CorporateAccountFrom) {
      this.CorporateAccountFrom[item] = row[item]
    }
    row.factoryArr.map(item => {
      item.companyId = item.factoryId
      item.companyName = item.factoryName
      $('#select2-roleSelect2Form-container').empty()
      $('#select2-roleSelect2Form-container').attr('title', item.factoryName)
      $('#select2-roleSelect2Form-container').prepend(item.factoryName)
    })
    this.companyArrays = row.factoryArr
    this.inputParam.companyId = row.companyId
    $('#roleSelect2Form').val(row.companyId).trigger('change')
    /**
     *  非常规开发:  单独处理角色问题,在变更角色名称,角色ID没有发生变化,编辑的时候拉角色接口数据,更新到最新的角色名称覆盖旧的数据
     */
    for (let item of this.companyList) {
      if (item.id == row.companyId) {
        this.CorporateAccountFrom.companyName = item.text
      }
    }
  }

  //资金明细
  financialDetails(row) {
    //路由传参接收
    // constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    //   activatedRoute.queryParams.subscribe(queryParams => {
    //     this.curPage = queryParams.nowPage || 1;
    //   });
    // }
    this.router.navigate(['/system/fund-details'], {
      queryParams: {
        id: row.id,
        accountName: row.accountName
      }
    })
  }
  /*
   * 关闭弹窗
   */
  modalClose(modal) {
    modal.hide()
    $('#CorporateAccountFrom').data('bootstrapValidator').resetForm()
    this.CorporateAccountFrom = {
      id: '',
      companyId: '',
      companyName: '',
      factoryArr: [],
      accountType: '',
      accountName: '',
      remark: ''
    }
    $('#roleSelect2Form').val('').trigger('change')
  }
  resetForm() {
    $('#CorporateAccountFrom').data('bootstrapValidator').resetForm()
    this.CorporateAccountFrom = {
      id: '',
      companyId: '',
      companyName: '',
      factoryArr: [],
      accountType: '',
      accountName: '',
      remark: ''
    }
    this.companyArrays = []
    $('#roleSelect2Form').val('').trigger('change')
  }
  /*
   * form提交
   */
  apiControlSubmit(modal) {
    $('#CorporateAccountFrom').bootstrapValidator('validate') //开启验证
    let isValid = $('#CorporateAccountFrom').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      if (!this.CorporateAccountFrom.companyId) {
        this.jsonApiService.message('请选择项目名称')
        return
      }
      if (this.CorporateAccountFrom.factoryArr.length === 0) {
        this.jsonApiService.message('请选择对接工厂')
        return
      }
      this.jsonApiService
        .http_obj('CorporAccount/edit.html', {
          data: JSON.stringify(this.CorporateAccountFrom)
        })
        .subscribe(data => {
          this.jsonApiService.message(data.message)
          if (data.success) {
            this.load()
            this.modalClose(modal)
          }
        })
    }
  }
}
